<template>
  <g-dialog
    width="50%"
    :title="getTitle"
    :visible.sync="dialogVisible"
    :isShowBtn="true"
    append-to-body
    :destroy-on-close="true"
    :beforeClose="hangleOnclose"
  >
    <div v-loading.fullscreen.lock="fullLoading">
      <el-form ref="form" :rules="rules" :model="form" label-width="100px" label-position="top">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="角色权限" prop="mark">
              <el-input v-model="form.mark" placeholder="请输入角色权限标识" />
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="角色是否启用" prop="status">
              <el-switch
                v-model="form.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              ></el-switch>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="角色描述" prop="desc">
              <el-input type="textarea" :rows="3" v-model="form.desc" placeholder="请输入角色描述" />
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="后台权限" prop="desc">
              <el-cascader-panel
                v-model="form.menus"
                :options="menuOpts"
                :props="defaultProps"
                @change="changeMenu"
              ></el-cascader-panel>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="g-dialog-bottom-action">
      <el-button @click="handleClose" size="small">取消</el-button>

      <el-button type="primary" @click="handleSubmit()" size="small">提交</el-button>
    </div>
  </g-dialog>
</template>

<script>
import { addRoleApi, updateRoleApi, detailRoleApi } from './role';
import { getMenuApi } from '@/api/menu-api';
export default {
  name: 'CreateRole',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    editId: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      localVisible: this.visible,
      fullLoading: false,
      handleThrottledSubmit: null,
      detailData: {},
      menuOpts: [],

      defaultProps: {
        value: 'id',
        label: 'name',
        checkStrictly: true, // 父子不关联
        emitPath: false, // false只返回当前节点的值 true返回节点值数组
        multiple: true // 多选
      },
      form: {
        name: '', // 名称
        mark: '', // 角色标识
        status: 1, // 类型
        menus: []
      },
      rules: {
        name: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  computed: {
    isUpdate() {
      return Boolean(this.editId);
    },
    getTitle() {
      return this.isUpdate ? '编辑角色' : '新增角色';
    },

    dialogVisible: {
      get() {
        return this.localVisible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    }
  },
  created() {},

  mounted() {
    this.getMenu();
    if (this.isUpdate) {
      this.getDetail();
    }
  },

  methods: {
    async getMenu() {
      try {
        const params = {};
        const { data } = await getMenuApi(params);
        this.menuOpts = data ?? [];
      } catch (err) {
        console.warn(err);
      }
    },

    async getDetail() {
      try {
        const { data } = await detailRoleApi(this.editId);

        this.form.name = data.name;
        this.form.mark = data.mark;
        this.form.desc = data.desc;
        this.form.status = data.status;
        this.form.menus = data.menus.map(({ id }) => id);
      } catch (err) {
        console.warn(err);
      } finally {
        this.fullLoading = false;
      }
    },

    beforeSubmit() {
      // 将 menu 转为 [{id: 1}]格式传入后端
      const menus = this.form.menus.map((item) => {
        return { id: item };
      });

      const params = {
        ...this.form,
        menus
      };
      return params;
    },
    handleSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false;

        try {
          this.fullLoading = true;

          let params = this.beforeSubmit();

          let _code = 0;
          if (this.isUpdate) {
            params.id = this.editId;
            const { code } = await updateRoleApi(params);
            _code = code;
          } else {
            const { code } = await addRoleApi(params);
            _code = code;
          }

          if (_code === 200) {
            this.$modal.msgSuccess('操作成功');
            this.handleClose();
          }
        } catch (err) {
          console.warn(err);
        } finally {
          this.fullLoading = false;
        }
      });
    },
    // 点击icon-close触发
    hangleOnclose() {
      this.handleClose();
    },

    handleClose() {
      this.dialogVisible = false;
      this.$emit('close-create');
    },

    changeType(val) {
      this.form.order = 1;
    },
    changeMenu(val) {
      console.log(val);
    }
  }
};
</script>

<style lang="scss" scoped></style>
